#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardPaths>
#include <QFileDialog>
#include <QPixmap>
#include <QPainter>
#include <QDropEvent>
#include <QMimeData>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow) {
    ui->setupUi(this);
    paramInit();
    uiInit();
    connectInit();
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::uiInit() {
    setWindowTitle("Img2Ico");
    setAcceptDrops(true);

    ui -> menuBar -> addMenu(opt_menu);
    ui -> menuBar -> addMenu(cfg_menu);
    ui -> menuBar -> addMenu(help_menu);

    opt_quit -> setShortcut(Qt::CTRL | Qt::Key_Q);
    opt_menu -> addAction(opt_quit);

    ui -> cbBoxStandardSize ->addItem("16  x 16", 16);
    ui -> cbBoxStandardSize ->addItem("32  x 32", 32);
    ui -> cbBoxStandardSize ->addItem("64  x 64", 64);
    ui -> cbBoxStandardSize ->addItem("128 x 128", 128);
    ui -> cbBoxStandardSize ->addItem("256 x 256", 256);

    ui -> rBtnStandardOut -> setChecked(true);

    ui -> lEditIcoLeng -> setDisabled(true);
    ui -> lEditIcoWid -> setDisabled(true);

    ui -> lEditIcoLeng -> setValidator(regexp_validator);
    ui -> lEditIcoWid -> setValidator(regexp_validator);


    ui -> statusBar -> addWidget(l_tip);
    ui -> statusBar -> addPermanentWidget(l_cpyright);
    ui -> statusBar -> setStyleSheet(QString("QStatusBar::item {border: 0}"));
}

void MainWindow::paramInit() {
    opt_menu = new QMenu(QStringLiteral("选项(&O)"), this);
    cfg_menu = new QMenu(QStringLiteral("设置(&C)"), this);
    help_menu = new QMenu(QStringLiteral("帮助(&H)"), this);

    opt_quit = new QAction(QStringLiteral("退出(&Q)"), this);

    regexp_validator = new QRegExpValidator(QRegExp("^[1-9][0-9]|1[0-9][0-9]|2[0-5][0-6]$"));
    timer = new QTimer();

    l_tip = new QLabel(tr("  暂无任何提示信息."));
    l_cpyright = new QLabel(tr(" Copyright © 2023-2032 我是混子我怕谁 版权所有"));

    clearImgUrl();
    clearFloderUrl();
    clearImg();
}

void MainWindow::connectInit() {
    //QAction
    connect(opt_quit, &QAction::triggered, this, &QMainWindow::close);

    //QPushButton
    connect(ui -> pBtnChooseImg, &QPushButton::clicked, [=]() {
        QString url;

        url = QFileDialog::getOpenFileName(this,
                                          tr("选择文件"),
                                          QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
                                          tr("图片文件(*.jpeg *.png *.jpg);;"));
        if(url != "") {
            setImgUrl(url);
            ui -> cBoxBkgFill ->isChecked() ? setShow(url) : setImg(url);
        }
    });

    connect(ui -> pBtnChooseFloder, &QPushButton::clicked, [=]() {
        QString url;

        url = QFileDialog::getExistingDirectory(this,
                                          tr("选择文件"),
                                          QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
        if(url != "") {
            setFloderUrl(url);
        }
    });

    connect(ui -> pBtnClearData, &QPushButton::clicked, [=]() {
        clearImgUrl();
        clearImg();
    });

    connect(ui ->pBtnStart, &QPushButton::clicked, [=]() {
        toIco(img_url);
    });

    //QCheckBox
    connect(ui -> cBoxBkgFill, &QCheckBox::stateChanged, [=](int state) {
        if(img_url == "") {
            return ;
        }

        state != 0 ? setShow(img_url) : setImg(img_url);
    });

    //QRadioButton
    connect(ui -> rBtnStandardOut, &QRadioButton::clicked, [=]() {
        ui -> cbBoxStandardSize -> setDisabled(false);
        ui -> lEditIcoLeng -> setDisabled(true);
        ui -> lEditIcoWid -> setDisabled(true);

        ui -> lEditIcoLeng -> setText("");
        ui -> lEditIcoWid -> setText("");
    });

    connect(ui -> rBtnCustomiseOut, &QRadioButton::clicked, [=]() {
        ui -> cbBoxStandardSize -> setDisabled(true);
        ui -> lEditIcoLeng -> setDisabled(false);
        ui -> lEditIcoWid -> setDisabled(false);

        ui -> lEditIcoLeng -> setText("16");
        ui -> lEditIcoWid -> setText("16");
    });

    //QTimer
    connect(timer, &QTimer::timeout, [=]() {
        l_tip -> setText(tr("  暂无任何提示信息."));
    });
}

void MainWindow::setImgUrl(QString url) {
    ui -> lImgUrl -> setText(url);
    ui -> lImgUrl -> setToolTip(tr(url.toLocal8Bit().data()));

    img_url = url;
}

void MainWindow::clearImgUrl() {
    ui -> lImgUrl -> setText("暂无图片路径信息，请选择图片");
    ui -> lImgUrl -> setToolTip(tr("暂无图片路径信息，请选择图片"));

    img_url = "";
}

void MainWindow::setFloderUrl(QString url) {
    floder_url = url;

    ui -> lFloderUrl -> setText(floder_url);
    ui -> lFloderUrl -> setToolTip(tr(floder_url.toLocal8Bit().data()));
}

void MainWindow::clearFloderUrl() {
    floder_url = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);

    ui -> lFloderUrl -> setText(floder_url);
    ui -> lFloderUrl -> setToolTip(floder_url);
}

void MainWindow::setImg(QString url) {
    QPixmap pmap(url);

    ui -> lImgSizeValue -> setText(QString("%1px * %2px").arg(pmap.width()).arg(pmap.height()));

    pmap = pmap.scaled(ICO_LEN, ICO_LEN, Qt::KeepAspectRatio);

    ui -> lImgShow -> setPixmap(pmap);
}

void MainWindow::clearImg() {
    ui -> lImgShow -> clear();

    ui -> lImgSizeValue -> setText(QString("0 * 0"));
}

void MainWindow::setShow(QString url) {
    QPixmap pmap(url), pmap_bkg(ICO_LEN, ICO_LEN);
    QPainter painter(&pmap_bkg);

    ui -> lImgSizeValue -> setText(QString("%1px * %2px").arg(pmap.width()).arg(pmap.height()));

    pmap = pmap.height() > pmap.width() ? pmap.scaledToHeight(ICO_LEN) : pmap.scaledToWidth(ICO_LEN);

    painter.fillRect(0, 0, ICO_LEN, ICO_LEN, Qt::white);

    pmap.height() > pmap.width() ?
    painter.drawPixmap((ICO_LEN - pmap.width()) / 2, 0, pmap.width(), pmap.height(), pmap) :
    painter.drawPixmap(0, (ICO_LEN - pmap.height()) / 2, pmap.width(), pmap.height(), pmap);

    ui -> lImgShow -> setPixmap(pmap_bkg);
}

void MainWindow::clearShow() {
    ui -> lImgShow -> clear();
}

void MainWindow::toIco(QString url) {
    int length, width;

    if(url == "") {
        l_tip -> setText("  请选择需要转换的图片！");
        timer -> start(5 * 1000);
        return ;
    }

    if(ui -> rBtnCustomiseOut -> isChecked()) {
        if(ui -> lEditIcoLeng -> text() == "" || ui -> lEditIcoWid -> text() == "") {
            l_tip -> setText("  自定义模式下长或宽不能为空！");
            timer -> start(5 * 1000);
            return ;
        }

        length = ui -> lEditIcoLeng -> text().toInt();
        width = ui -> lEditIcoWid -> text().toInt();
    }
    else {
        length = width = ui -> cbBoxStandardSize -> currentData().toInt();
    }

    if(ui -> lEditFileName -> text() == "") {
        l_tip -> setText("  文件名不能为空！");
        timer -> start(5 * 1000);
        return ;
    }

    QPixmap pmap(url), pmap_bkg(length, width);
    QPainter painter(&pmap_bkg);

    pmap = pmap.height() > pmap.width() ? pmap.scaledToHeight(width) : pmap.scaledToWidth(length);

    if(ui -> cBoxBkgFill -> isChecked()) {
        painter.fillRect(0, 0, length, width, Qt::white);
        painter.drawPixmap(pmap.height() > pmap.width() ? (length - pmap.width()) / 2 : 0,
                           pmap.height() > pmap.width() ? 0 : (width - pmap.height()) / 2,
                           pmap.width(), pmap.height(), pmap);

        pmap = pmap_bkg;
    }

    pmap.save(QString("%1/%2.ico").arg(floder_url, ui -> lEditFileName -> text()), "ico");

    l_tip -> setText("  转换完毕！");
    timer -> start(5 * 1000);
}

void MainWindow::dragEnterEvent(QDragEnterEvent *e) {
    e -> acceptProposedAction();
}

void MainWindow::dragLeaveEvent(QDragLeaveEvent *e) {
    Q_UNUSED(e);
}

void MainWindow::dropEvent(QDropEvent *e) {
    QList<QUrl> urls = e -> mimeData() -> urls();

    if(urls.length() != 1) {
        l_tip -> setText(tr("  不接受多个文件，请拖拽单个文件！"));
        timer -> start(5 * 1000);
        return;
    }

    QString url = urls[0].path().mid(1);

    if(QFileInfo(url).isDir()) {
        l_tip -> setText(tr("  不接受文件夹，请拖拽单个文件！"));
        timer -> start(5 * 1000);
        return;
    }

    if(!(url.contains(".png") || url.contains(".jpg") || url.contains(".jpeg") || url.contains(".bmp"))) {
        l_tip -> setText(tr("  只接受PNG、JPG、JPEG、BMP格式图片！"));
        timer -> start(5 * 1000);
        return;
    }

    setImgUrl(url);
    ui -> cBoxBkgFill ->isChecked() ? setShow(url) : setImg(url);
}
